<template>
  <div>
    <cus-modal
      ref="modal"
      :title="form.id == '' ? '添加' : '编辑'"
      @on-visible-change="onVisibleChange"
      width="760"
      @onOk="onOk"
    >
      <Form
        ref="formValidate"
        :model="form"
        :rules="ruleValidate"
        :label-width="110"
      >
        <FormItem label="供应商名称" prop="name">
          <Input
            v-model="form.name"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入供应商"
            :disabled="Boolean(form.id)"
          ></Input>
        </FormItem>
        <FormItem
          label="供应商编码"
          prop="supplyCode"
          :rules="[
            {
              required: true,
              message: '供应商编码不能为空',
              trigger: 'blur'
            },
            {
              required: true,
              message: '供应商编码只能字母或数字',
              pattern: '^[0-9a-zA-Z]*$',
              trigger: 'blur'
            }
          ]"
        >
          <Input
            v-model="form.supplyCode"
            clearable
            maxlength="20"
            style="width: 200px"
            :disabled="Boolean(form.id)"
            placeholder="请输入供应商编码"
          ></Input>
        </FormItem>
        <FormItem
          label="供应种类"
          prop="materialClassValue"
          :rules="{
            required: true,
            type: 'array',
            message: '供应种类不能为空',
            trigger: 'change'
          }"
        >
          <Select
            class="selectItem"
            multiple
            filterable
            v-model="form.materialClassValue"
            :max-tag-count="1"
            style="width: 200px"
          >
            <Option
              v-for="item in materialClassTree"
              :disabled="item.isSupplyCheck == 1"
              :value="item.id"
              :key="item.id"
              >{{ item.categoryName }}</Option
            >
          </Select>
        </FormItem>
        <FormItem
          label="联系人"
          prop="contact"
          :rules="[
            {
              required: true,
              message: '联系人不能为空',
              trigger: 'blur'
            },
            {
              required: true,
              message: '联系人只能汉字、数字、字母',
              pattern: '^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$',
              trigger: 'blur'
            }
          ]"
        >
          <Input
            v-model="form.contact"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入联系人"
          ></Input>
        </FormItem>
        <FormItem
          label="电话号码"
          prop="mobile"
          :rules="[
            {
              required: 'true',
              message: '电话号码不能为空',
              trigger: 'blur'
            }
          ]"
        >
          <Input
            v-model="form.mobile"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入电话号码"
          ></Input>
        </FormItem>
        <FormItem
          label="地址"
          prop="address"
          :rules="{ required: true, message: '地址不能为空', trigger: 'blur' }"
        >
          <Input
            v-model="form.address"
            clearable
            maxlength="150"
            style="width: 200px"
            placeholder="请输入地址"
          ></Input>
        </FormItem>
        <FormItem label="邮箱地址" prop="email" class="redDot">
          <Input
            v-model="form.email"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入邮箱地址"
          ></Input>
        </FormItem>
        <FormItem label="资质有效期">
          <DatePicker
            type="daterange"
            show-week-numbers
            transfer
            ref="formDate"
            :value="dateTime"
            @on-change="datePickerChange"
            placement="bottom-end"
            placeholder="开始日期 - 结束日期"
            style="width: 200px"
          />
        </FormItem>
        <FormItem label="资质文件">
          <Upload
            ref="upload"
            :show-upload-list="false"
            :format="['jpg', 'jpeg', 'png']"
            :max-size="10240"
            accept="image/jpeg,image/jpg,image/png"
            :before-upload="handleBeforeUpload"
            multiple
            type="drag"
            action=""
            style="display: inline-block; width: 58px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
        </FormItem>
        <div class="imgContent" v-if="uploadList.length > 0">
          <!-- 准备上传的图片列表 -->
          <div
            class="imgContent-item"
            v-for="(item, index) in uploadList"
            :key="index"
            :style="{ marginLeft: (index + 1) % 4 == 0 ? '0' : '50px' }"
          >
            <img :src="item" alt="" style="width: 100%; height: 100%" />
            <div class="imgContent-item-cover">
              <Icon type="ios-eye-outline" @click="handleView(item)"></Icon>
              <Icon
                type="ios-trash-outline"
                @click="handleRemove(item, index)"
              ></Icon>
            </div>
          </div>
        </div>
      </Form>
      <Spin size="large" fix v-if="loading"></Spin>
      <!--预览图片-->
      <imgPreview ref="imgPreview"></imgPreview>
    </cus-modal>
  </div>
</template>

<script>
import {
  postApiSupplierIssuppliername,
  postApiPurchasingSupplierSave,
  postApiPurchasingSupplierUpdate,
  getCategoryListWithSupplyStatus,
  deleteApiCertificationPicture
} from "@/api/business/manager";
import imgPreview from "./imgPreview.vue";

const form = {
  id: "",
  name: "", //供应商名称
  materialClassValue: [], // 供应商种类
  supplyCode: "", // 供应商编码
  contact: "", // 联系人
  mobile: "", // 电话号码
  address: "", // 地址
  email: "", // Email邮箱
  startTime: "", // 资质有效期开始时间
  stopTime: "", // 资质有效期结束时间
  uploadFiles: [] //上传资质文件
};

export default {
  name: "addDistinctionModal",
  components: { imgPreview },
  data() {
    const validatePass = (rule, value, callback) => {
      let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
      if (!value) {
        callback(new Error("供应商名称不能为空"));
      } else if (!value.match(reg)) {
        callback(new Error("名称只能汉字、数字、字母"));
      } else {
        postApiSupplierIssuppliername({
          supplierName: value
        }).then(res => {
          if (res.retCode == 2000) {
            callback();
          } else if (res.retCode == 2999) {
            callback(new Error("已经存在该供应商"));
          }
        });
      }
    };
    return {
      loading: false,
      ruleValidate: {
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // 如果邮箱存在
              if (value) {
                if (this.$cu.test.email(value)) {
                  callback();
                } else {
                  return callback(new Error("邮箱格式错误"));
                }
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        name: [{ validator: validatePass, trigger: "blur" }]
      },
      form: form,
      materialClassTree: [], //食材种类数据
      uploadList: [], //图片列表集合
      imgPreviewUrl: "", //图片地址
      dateTime: [] //资质时间
    };
  },
  mounted() {
    this.form = this.$cu.deepClone(form);
  },
  methods: {
    onVisibleChange(v) {
      this.$refs["formValidate"].resetFields();
      this.$refs.formDate.handleClear(); //清空时间
      if (!v) this.form = this.$cu.deepClone(form);
    },
    show() {
      this.$refs["modal"].show = true;
      if (this.form.id) {
        let l = row.materialClass.replace("[", "");
        let t = l.replace("]", "");
        let arr = t.split(",");
        arr.forEach(element => {
          element = element.replace(" ", "");
          this.$nextTick(() => {
            this.form.materialClassValue.push(element);
          });
        });
      }
      this.getCategoryListWithSupplyStatusApi();
    },
    datePickerChange(date) {
      this.form.startTime = date[0];
      this.form.stopTime = date[1];
    },
    onOk() {
      this.$refs["formValidate"].validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.form.id) {
            this.postApiPurchasingSupplierUpdateApi();
          } else {
            this.postApiPurchasingSupplierSaveApi();
          }
        }
      });
    },
    handleBeforeUpload(file) {
      if (this.uploadList.length <= 2) {
        const _this = this;
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          // 文件base64
          const fileBase64 = this.result;
          _this.uploadList.push(fileBase64);
          _this.form.uploadFiles.push(file);
        };
      } else {
        this.$Message.info("最多可添加三张文件！");
      }
      console.log(this.form.uploadFiles);
      return;
    },
    handleView(v) {
      this.$refs["imgPreview"].show(v);
      this.$refs["imgPreview"].imgPreviewUrl = v;
    },
    handleRemove(file, index) {
      this.uploadList.splice(index, 1);
      this.form.uploadFiles.splice(index, 1);
      this.deleteApiCertificationPictureApi(file);
      console.log(this.form.uploadFiles);
    },
    //添加供应商信息前效验----------------接口
    postApiSupplierIssuppliernameApi() {
      return new Promise(resolve => {
        postApiSupplierIssuppliername({
          supplierName: this.form.name
        }).then(res => {
          if (res.code === 2000) {
            resolve();
          }
        });
      });
    },
    //添加供应商信息---------------------接口
    postApiPurchasingSupplierSaveApi() {
      console.log(this.form.uploadFiles);
      return new Promise(resolve => {
        let params = new FormData();
        params.append("name", this.form.name);
        params.append("supplyCode", this.form.supplyCode);
        params.append("contact", this.form.contact);
        params.append("mobile", this.form.mobile);
        params.append("address", this.form.address);
        params.append("email", this.form.email);
        params.append("startTime", this.form.startTime);
        params.append("stopTime", this.form.stopTime);
        params.append("materialClassValue", this.form.materialClassValue);
        params.append("file1", this.form.uploadFiles[0]);
        params.append("file2", this.form.uploadFiles[1]);
        params.append("file3", this.form.uploadFiles[2]);
        postApiPurchasingSupplierSave(params).then(res => {
          this.loading = false;
          if (res.retCode === 2000) {
            this.$Message.success(res.retMsg);
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    //编辑供应商信息---------------------接口
    postApiPurchasingSupplierUpdateApi() {
      console.log(this.form.uploadFiles);
      return new Promise(resolve => {
        let params = new FormData();
        params.append("id", this.form.id);
        params.append("name", this.form.name);
        params.append("supplyCode", this.form.supplyCode);
        params.append("contact", this.form.contact);
        params.append("mobile", this.form.mobile);
        params.append("address", this.form.address);
        params.append("email", this.form.email);
        params.append("startTime", this.form.startTime);
        params.append("stopTime", this.form.stopTime);
        params.append("materialClassValue", this.form.materialClassValue);
        params.append("file1", this.form.uploadFiles[0]);
        params.append("file2", this.form.uploadFiles[1]);
        params.append("file3", this.form.uploadFiles[2]);
        postApiPurchasingSupplierUpdate(params).then(res => {
          this.loading = false;
          if (res.retCode === 2000) {
            this.$Message.success(res.retMsg);
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    //供应种类接口------------------------------接口
    getCategoryListWithSupplyStatusApi() {
      this.materialClassTree = [];
      return new Promise(resolve => {
        getCategoryListWithSupplyStatus(this.data).then(res => {
          if (res.retCode == 2000) {
            this.materialClassTree = res.data;
            resolve();
          }
        });
      });
    },
    //删除图片---------------------接口
    deleteApiCertificationPictureApi(url) {
      return new Promise(resolve => {
        let params = {
          id: this.form.id,
          url: url
        };
        deleteApiCertificationPicture(params).then(res => {
          if (res.retCode == 2000) {
            this.$Message.success("删除成功");
            resolve();
          }
        });
      });
    }
  }
};
</script>

<style scoped lang="less">
.redDot {
  /deep/.ivu-form-item-label:before {
    content: "";
    margin-right: 0px;
  }
}
.selectItem {
  /deep/.ivu-select-input {
    height: 35px !important;
    line-height: 35px;
  }
}
.imgContent {
  width: 100%;
  height: 120px;
  display: flex;
  align-items: center;

  &-item {
    height: 100%;
    width: 170px;
    position: relative;
    text-align: center;
    line-height: 120px;
    display: inline-block;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    &-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
    }
  }
  &-item:hover &-item-cover {
    display: block;
  }
  &-item-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
}
</style>
